package com.gxwgy.wg2404.bank.service.impl;


import com.gxwgy.wg2404.bank.dao.AccountDao;
import com.gxwgy.wg2404.bank.dao.AccountDaoImpl;
import com.gxwgy.wg2404.bank.exceptions.MoneyNoEnoughException;
import com.gxwgy.wg2404.bank.pojo.Account;
import com.gxwgy.wg2404.bank.service.AccountService;
import com.gxwgy.wg2404.bank.utils.DBUtil;


import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 姚相国
 * @version 1.0
 * @className AccountService
 * @date 2024/10/13 16:58
 * Service被翻译为: 业务
 * AccountService中专门除了Account业务的一个类
 * 在此类中应该只编写纯业务代码
 */
public class AccountServiceImpl implements AccountService {
    // 这里方法起名一定要体现出，处理什么方法的业务

    //new AccountDao
    private AccountDao accountDao = new AccountDaoImpl();

    /**
     * 完成转账的业务逻辑
     * @param fromAccount 转出账号
     * @param toAccount 转入账号
     * @param money 转账金额
     */
    public void transfer(String fromAccount,String toAccount,double money)
            throws MoneyNoEnoughException {
        //service层控制事务
        try (Connection connection = DBUtil.getConnection();){
            //开启事务
            connection.setAutoCommit(false);

            // 查询余额是否充足
            // 先查转出账号的余额，如果余额充足跳到else
            Account fromAct = accountDao.selectByAccount(fromAccount); //转出
            Account toAct = accountDao.selectByAccount(toAccount);// 转入

            if (fromAct.getBalance() < money) {
                throw new MoneyNoEnoughException("对不起余额不足!!");

            }else {
                // 程序到这里说明余额充足
                //修改余额(只是修改Java内存中的对象的余额)
                fromAct.setBalance(fromAct.getBalance() - money);
                toAct.setBalance(toAct.getBalance() + money);
                // 执行数据库的更新操作
                int count = accountDao.update(fromAct);
                count += accountDao.update(toAct);
                if (count != 2) {
                    throw new MoneyNoEnoughException("账户转账异常!!");
                }
            }
            //提交事务
            connection.commit();

        } catch (SQLException e) {
            throw new MoneyNoEnoughException("账户转账异常!!");
        }

    }
}
